// 请求接口域名
const requestUrlDomain = "https://www.jiaxiaoyanfang.com/vision";

// 默认请求超时时间（单位：ms)
const timeout = 30000;

// 处理token失效 -> 跳登录页重新登录
const handleTokenInvalid = function (data) {
  wx.showToast({
    icon: 'none',
    title: data.msg || '请求异常，请稍后再试'
  })
  wx.removeStorageSync('inspector-info')
  wx.removeStorageSync('service-info')
  setTimeout(() => {
    wx.redirectTo({
      url: '/pages/my/index',
    })
  }, 1000)

  // logout()
  // const currentPage = getCurrentPage()
  // const {
  //   route: currentRoute,
  //   options: currentRouteOptions
  // } = currentPage
  // wx.redirectTo({
  //   url: `../login/login?redirect=${currentRoute}&redirectOpts=${JSON.stringify(currentRouteOptions)}`,
  // })
  // goLogin();
}

// 封装网络请求方法
const request = function (url, data, method, opts = {}) {
  // 默认请求头
  const defaultHeader = {
    token: wx.getStorageSync("token"),
  };
  // 加载loading
  if (opts.showLoading !== false) {
    wx.showLoading({
      title: '加载中...',
    })
  }
  return new Promise((resolve, reject) => {
    const requestTask = wx.request({
      url: requestUrlDomain + url,
      data: {
        ...data,
      },
      method,
      timeout: opts.timeout || timeout,
      header: {
        ...defaultHeader,
        ...(opts.header || {})
      },
      success(res) {
        // console.log('request success')
        const {
          data,
          statusCode,
          header,
          cookies,
          profile
        } = res
        if (statusCode === 200) {
          if (data.code == 200) {
            resolve(data)
          } else {
            if (data.code == 401) {
              // token失效
              handleTokenInvalid(data)
              return;
            }
            // 如果接口要自己处理不同code状态（默认统一处理）
            if (opts.handleError) {
              reject(data)
            } else {
              // 统一处理code非0场景
              reject(data)
              setTimeout(() => {
                wx.showToast({
                  icon: 'none',
                  title: data.msg || '网络异常，请稍后再试'
                })
              }, 100)
            }
          }
        } else if (statusCode === 401) {
          // token失效
          handleTokenInvalid()
        }
      },
      fail(res) {
        // console.log('request fail')
        const {
          data,
          statusCode,
          header,
          cookies,
          profile
        } = res
        reject(data)
      },
      complete(res) {
        // console.log('request complete')
        wx.hideLoading()
        const {
          complete
        } = opts
        complete && complete(res)
      }
    })
    // 获取requestTask实例
    const {
      getRequestTask
    } = opts
    if (getRequestTask) {
      getRequestTask(requestTask)
    }
  })
}

function methodFactory(method) {
  return function (url, data, opts = {}) {
    return request(url, data, method, opts)
  }
}


request.get = methodFactory("GET")
request.post = methodFactory("POST")
request.delete = methodFactory("DELETE")
request.put = methodFactory("PUT")

module.exports = {
  request,
  requestUrlDomain,
  handleTokenInvalid
}